import { Effect, ImmerReducer, Reducer, Subscription, history  } from 'umi';

// 数据请求的方法
import { loginFn } from '@/api/user'

// 给全局状态中的属性添加类型
export interface AdminModelState {
  adminname: string;
  role: number
  token: string
  checkedkeys: string[]
  loginState: boolean
}

export interface AdminModelType {
  namespace: 'admin';
  state: AdminModelState;
  effects: {
    loginAction: Effect;
  };
  reducers: {
    // change_info: Reducer<AdminModelState>;
    // 启用 immer 之后
    change_info: ImmerReducer<AdminModelState>;
  }
}

const AdminModel: AdminModelType = {
  namespace: 'admin',
  // 用来放全局状态的地方
  state: {
    // 全局状态
    adminname: localStorage.getItem('adminname') || '',
    role: Number(localStorage.getItem('role')) || 1,
    checkedkeys: JSON.parse(localStorage.getItem('checkedkeys') as string) || [],
    loginState: localStorage.getItem('loginState') === 'true',
    token: localStorage.getItem('token') || ''
  },
  // 用来放异步的地方
  effects: {
    *loginAction({ payload }, { call, put }):any {
      // 触发数据请求的函数
      const res = yield call(loginFn, payload)
      if(res.data.code === '200'){
        // 触发 reducers 中的函数
        yield put({
          type: 'change_info',
          payload: res.data.data
        })
      }
    },
  },
  // 修改全局状态的地方
  reducers: {
    change_info(state: AdminModelState, action: any) {
      // 状态的修改
      // console.log(state,action.payload);
      // 保存在本地
      localStorage.setItem('adminname', action.payload.adminname)
      localStorage.setItem('role', action.payload.role)
      localStorage.setItem('token', action.payload.token)
      localStorage.setItem('loginState', 'true')
      localStorage.setItem('checkedkeys', JSON.stringify(action.payload.checkedkeys))

      // 保存在全局管理
      state.adminname = action.payload.adminname
      state.loginState = true
      state.checkedkeys = action.payload.checkedkeys
      state.role = action.payload.role
      state.token = action.payload.token
      // 跳转到首页
      history.push('/')
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  }
};

export default AdminModel;
